<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\VerificationCode;
use Illuminate\Support\Facades\Cache;

class VerificationController extends Controller
{
    public function send(Request $request)
    {
        \Log::info('Verification request received', ['email' => $request->email]);
        
        try {
            // 生成6位随机验证码
            $code = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            
            // 将验证码保存到缓存中，设置5分钟过期
            Cache::put('verification_code_' . $request->email, $code, now()->addMinutes(5));
            
            // 发送邮件
            Mail::to($request->email)->send(new VerificationCode($code));
            
            \Log::info('Verification code sent', [
                'email' => $request->email,
                'code' => $code
            ]);
            
            return response()->json([
                'success' => true,
                'message' => '验证码已发送到您的邮箱'
            ]);
        } catch (\Exception $e) {
            \Log::error('Verification error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '发送验证码失败：' . $e->getMessage()
            ], 500);
        }
    }

    public function verify(Request $request)
    {
        \Log::info('Verification attempt', ['email' => $request->email, 'code' => $request->code]);
        
        try {
            $storedCode = Cache::get('verification_code_' . $request->email);
            
            if (!$storedCode) {
                return response()->json([
                    'success' => false,
                    'message' => '验证码已过期，请重新发送'
                ]);
            }

            if ($storedCode !== $request->code) {
                return response()->json([
                    'success' => false,
                    'message' => '验证码错误'
                ]);
            }

            // 验证成功后删除缓存中的验证码
            Cache::forget('verification_code_' . $request->email);

            return response()->json([
                'success' => true,
                'message' => '验证成功'
            ]);
        } catch (\Exception $e) {
            \Log::error('Verification error', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return response()->json([
                'success' => false,
                'message' => '验证失败：' . $e->getMessage()
            ], 500);
        }
    }
} 